﻿using NetDisk.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace NetDisk.Dtos
{
    public class CreateDirDto : IValidatableObject
    {
        [Exists]
        public int ParentId { get; set; }
        [Required(ErrorMessage = "文件夹名不能为空")]
        public string Name { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var db = validationContext.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            var createDirDto = validationContext.ObjectInstance as CreateDirDto;
            var parentId = createDirDto.ParentId == 0 ? null : createDirDto.ParentId as int?;
            var dirFile = db.UploadFiles
                .Where(f => f.ParentId == parentId
                    && f.RealName == createDirDto.Name
                    && f.IsDir == true)
                .FirstOrDefault();

            if (dirFile != null)
            {
                yield return new ValidationResult($"{dirFile.Id}|文件夹 {createDirDto.Name} 已经存在, 不能重复创建!", new[] { nameof(Name) });
            }
        }
    }
}
